package com.mikao.service.impl;

import com.mikao.config.CdnProperties;
import com.mikao.dao.AdvDao;
import com.mikao.dto.bo.AdvForm;
import com.mikao.dto.bo.ReqDataTableDto;
import com.mikao.dto.vo.AdvDto;
import com.mikao.dto.vo.RspDataTableDto;
import com.mikao.entity.Adv;
import com.mikao.service.AdvService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @author KennyDavid
 */

@Service
public class AdvServiceImpl implements AdvService {

    @Value("${cdn.baseUrl}")
    private String cdn;
    private AdvDao advDao;
    private final CdnProperties cdnProperties;

    public AdvServiceImpl(AdvDao advDao, CdnProperties cdnProperties) {
        this.advDao = advDao;
        this.cdnProperties = cdnProperties;
    }

    @Override
    public RspDataTableDto<AdvDto> getAdvList(ReqDataTableDto dataTableDTO, String nameOrMobile) {
        List<AdvDto> dtos = new ArrayList<>();
        PageRequest pageRequest = new PageRequest(dataTableDTO.getPage(), dataTableDTO.getLength(),
                new Sort(Sort.Direction.DESC, "createTime"));

        Page<Adv> page = advDao.findAll((root, criteriaQuery, criteriaBuilder) -> {
            return null;
        }, pageRequest);

        AdvDto advDto;
        for (Adv adv : page.getContent()) {
            advDto = new AdvDto();
            BeanUtils.copyProperties(adv, advDto);
            dtos.add(advDto);
        }
        return new RspDataTableDto<>(dataTableDTO.getDraw(), page.getTotalElements(), dtos);
    }

    @Override
    public void removeAdv(Long id) {
        advDao.delete(id);
    }

    @Override
    public Boolean addAdv(AdvForm advForm) {
        Adv adv = new Adv();
        BeanUtils.copyProperties(advForm, adv);

        MultipartFile file = advForm.getImageUrl();
        File f = new File(cdnProperties.getBasePath());
        if (!f.exists()) {
            f.mkdirs();
        }

        String oldName = file.getOriginalFilename();
        String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."));

        File newFile = new File(f.getAbsolutePath(), newName);
        try {
            newFile.createNewFile();
            file.transferTo(newFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        adv.setImageUrl(cdn + newName);
        advDao.saveAndFlush(adv);
        return true;
    }

}
